using UnityEngine;
using System.Collections;

public class Seek : MonoBehaviour {
	
	private Vector3 spawnPoint;
	private GameObject target;
	private OTAnimatingSprite sprite;
	public float speed = 0.2f;
	private bool alive = true;
	// Use this for initialization
	void Start () {
	
		spawnPoint = transform.position; // player will respawn at initial starting point
		
		sprite = GetComponent<OTAnimatingSprite>();
	    // Set this sprite's collision delegate 	    
	    sprite.onCollision = OnCollision;
		sprite.onExit = OnExit;		
		
		target = GameObject.Find("player_anim_sprite");
	
	}
	
	// Update is called once per frame
	void Update () {
	
		if(alive){
			Vector3 diferenca = target.transform.position - transform.position;
			diferenca.Normalize();
			diferenca.x *= speed;
			diferenca.y *= speed;
			diferenca.z *= 0;
			
			transform.position = transform.position + diferenca;
			
			Vector3 eulerAngles = transform.eulerAngles;
			eulerAngles.z = Mathf.Atan2(-diferenca.x, diferenca.y) * Mathf.Rad2Deg;
			
			transform.eulerAngles = eulerAngles;
		}
					
	}
	
	/**
	 * Collid with only orthello OTObject
	 */
	// OnCollision delegate is called when star collides with another 'collidable' object
    // HINT - OnEnter and OnCollision delegates are called exactly at the same time, the only
    // difference is their naming convention
    /// <exclude />
	public void OnCollision(OTObject owner)
	{
	
		if (owner.collisionObject.tag.IndexOf("missile_tag") == 0){
			return;
		}
		
		
		//owner.visible = false;
//		transform.position = spawnPoint;						
		if(alive){
			 foreach (Transform child in transform) {
				Destroy(child.gameObject);
			}
			alive = false;
			sprite.Play("explosion");
			sprite.destroyWhenFinished = true;
		}
		
	}
	
	// OnStay delegate is called when star enters (overlaps) another 'collidable' object
    // !IMPORTANT - This sprite's collidable setting has to be true otherwide
    // collision delegates will not be called
    /// <exclude />	
	public void OnStay(OTObject owner)
	{
	}
	
	// OnExit delegate is called when star no longer overlaps another 'collidable' object
    /// <exclude />
	public void OnExit(OTObject owner)
	{									
	}	
	
}
